<?php
/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

defined('AUTH_SERVICE') or define('AUTH_SERVICE', 'google');

require_once '../server.php';
require_once '../../library/googleapi/apiClient.php';

$client = new apiClient();
$client -> setApplicationName('Google About Me!');
$client -> setScopes(array(
    'http://www.google.com/m8/feeds/',
    'https://www.googleapis.com/auth/userinfo.profile',
    'https://www.googleapis.com/auth/userinfo.email'
));
// Documentation: http://code.google.com/apis/gdata/docs/2.0/basics.html
// Visit https://code.google.com/apis/console?api=contacts to generate your
// oauth2_client_id, oauth2_client_secret, and register your oauth2_redirect_uri.
$client -> setClientId(GOOGLE_KEY);
$client -> setClientSecret(GOOGLE_SECRET);
$client -> setRedirectUri(AUTH_BASE_URL . '/google/contact.php');


//$client->setDeveloperKey('insert_your_developer_key');

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
 $client->setAccessToken($_SESSION['token']);
}

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['token']);
  $client->revokeToken();
}

if ($client->getAccessToken()) {
  $req = new apiHttpRequest("https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=1000");
  $val = $client->getIo()->authenticatedRequest($req);

  // The contacts api only returns XML responses.
  $data = json_decode($val->getResponseBody(), true);
  $contacts =  array();
  
  foreach($data['feed']['entry'] as $entry)
  {
	
	$email =  $entry['gd$email'][0]['address'];
	
	$name = $entry['title']['$t'];
	
	if($name == '' or $name  == ' ')
	{
		$name = $email;
	}
	
	if(empty($email))
	{
		continue;
	}
	$contacts[] = array('email'=>$email,'name'=>$name);
	
 }


$encodeContact = urlencode(json_encode($contacts));

$sSecurityToken =  @$_SESSION['security_token'];

$token_name =  @$_SESSION['token_name'];

if($token_name == "")
{
	$token_name = "phpfox[security_token]";
}

$sUrlCallback = AUTH_CALLBACK_URL;

$sForm ='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
	<html>
		<head>
			<title></title>	
		</head>
		<body>
	<form action="'.$sUrlCallback.'" method="POST" id="postform" style="visible:hide">
	<input type="hidden" name="'.$token_name.'" value="'.$sSecurityToken.'"/>
	<input name="contact" type="hidden" value="'.$encodeContact.'"/>
	<input name="get_success" type="hidden" value="1" />
	</form>
	<script language="JavaScript" type="text/javascript">			
		function submitForm()
		{
			document.getElementById("postform").submit();		
		}		
		submitForm();
	</script>    </body>
	</html>';
	echo $sForm;				
	exit();
	
  
   // The access token may have been updated lazily.
  $_SESSION['token'] = $client->getAccessToken();
} else {
  $auth = $client->createAuthUrl();
}

if (isset($auth)) {
	header('location: '. $auth);
} else {
    print "<a class=logout href='?logout'>Logout</a>";
}